package com.ruoyi.quartz.task;


import com.alibaba.fastjson.JSONObject;
import com.snowRemovingUser.domain.MDevice;
import com.snowRemovingUser.domain.MDeviceAttribute;
import com.snowRemovingUser.mapper.MDeviceAttributeMapper;
import com.snowRemovingUser.mapper.MDeviceAttributeSlaveMapper;
import com.snowRemovingUser.mapper.MDeviceMapper;
import com.snowRemovingUser.util.DateUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时检查设备属性
 */
@Component("deviceAttributeTask")
public class DeviceAttributeTask {

    /** log */
    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private MDeviceMapper deviceMapper;

    @Value("${jiutong.weather-data.url}")
    private String weatherDataUrl;

    @Value("${kemin.weather-data.url}")
    private String keMinDataUrl;

    @Value("${kemin.weather-data.mobile}")
    private String mobile;

    @Value("${kemin.weather-data.password}")
    private String password;

    @Autowired
    private MDeviceAttributeMapper mDeviceAttributeMapper;

    @Autowired
    private MDeviceAttributeSlaveMapper mDeviceAttributeSlaveMapper;


    public void start(){


        try {

            MDevice mDevice = new MDevice();
            List<MDevice> mDevices = deviceMapper.selectMDeviceList(mDevice);

            // 九通的数据
            List<MDevice> JiuTongDevices = mDevices.stream().filter(p -> p.getDeviceType().contains("01")).collect(Collectors.toList());
            // 科敏的数据
            List<MDevice> KeMinDevices = mDevices.stream().filter(p -> p.getDeviceType().contains("02")).collect(Collectors.toList());

            // 处理九通数据
            for (MDevice jiuTongDevice : JiuTongDevices) {

                List<Map<String, Object>> jiuTongData = getJiuTongData(jiuTongDevice.getSerialNumber());

                for (Map<String, Object> jiuTongDataMap : jiuTongData) {

                    MDeviceAttribute mDeviceAttribute = new MDeviceAttribute();
                    mDeviceAttribute.setSerialNumber(jiuTongDataMap.get("device_id").toString());
                    mDeviceAttribute.setAttributeId(jiuTongDataMap.get("attribute_id").toString());
                    mDeviceAttribute.setAttributeName(jiuTongDataMap.get("attribute_name").toString());
                    mDeviceAttribute.setAttributeValue(jiuTongDataMap.get("attribute_value").toString());
                    mDeviceAttribute.setAttributeUnit(jiuTongDataMap.get("attribute_unit").toString());
                    mDeviceAttribute.setDeviceType("01");
                    //时间转换
                    Long time = (Long) jiuTongDataMap.get("time");
                    Date date = new Date(time);
                    mDeviceAttribute.setAttributeDate(date);

                    Date newDate = new Date();
                    //如果时间超过1小时就视为离线
                    if (newDate.getTime() -time > 3600000){

                        mDeviceAttribute.setAttributeStatus(1);

                    }else {

                        mDeviceAttribute.setAttributeStatus(0);
                    }

                    MDeviceAttribute deviceAttribute =mDeviceAttributeMapper.selectMDeviceAttributeBySerialNumberAndAttributeId(mDeviceAttribute.getSerialNumber(),mDeviceAttribute.getAttributeId());

                    if (deviceAttribute==null){

                        mDeviceAttributeMapper.insertMDeviceAttribute(mDeviceAttribute);
                        //logger.info("九通"+mDeviceAttribute.getSerialNumber()+mDeviceAttribute.getAttributeName()+"添加设备最新属性状态成功");
                    } else if (deviceAttribute.getAttributeStatus()!=2){

                        mDeviceAttributeMapper.updateMDeviceAttributeBySerialNumberAndAttributeId(mDeviceAttribute);
                        //logger.info("九通"+mDeviceAttribute.getSerialNumber()+mDeviceAttribute.getAttributeName()+"更新设备最新属性状态成功");
                    }
                }
            }


            //处理科敏数据
            for (MDevice keMinDevice : KeMinDevices) {


                List<Map> keMinData = getKeMinData(keMinDevice.getSerialNumber());


                for (Map keMinDatum : keMinData) {

                    MDeviceAttribute mDeviceAttribute = new MDeviceAttribute();
                    mDeviceAttribute.setSerialNumber(keMinDevice.getSerialNumber());
                    mDeviceAttribute.setAttributeId("road_temperature");
                    mDeviceAttribute.setAttributeName("路温");
                    mDeviceAttribute.setAttributeValue(keMinDatum.get("avgTemp").toString());
                    mDeviceAttribute.setAttributeUnit("℃");
                    mDeviceAttribute.setDeviceType("02");
                    //时间需要转换
                    String reportDate =  keMinDatum.get("reportDate").toString();
                    Date reportDates = DateUtil.toDate(reportDate, "yyyy-MM-dd HH:mm:ss");
                    mDeviceAttribute.setAttributeDate(reportDates);

                    Date newDate = new Date();
                    //如果时间超过1小时就视为离线
                    if (newDate.getTime() -reportDates.getTime() > 3600000){

                        mDeviceAttribute.setAttributeStatus(1);

                    }else {

                        mDeviceAttribute.setAttributeStatus(0);
                    }

                    //查询科敏的数据
                    MDeviceAttribute deviceAttribute = mDeviceAttributeMapper.selectMDeviceAttributeBySerialNumberAndAttributeId(mDeviceAttribute.getSerialNumber(), mDeviceAttribute.getAttributeId());

                    if (deviceAttribute==null){

                        mDeviceAttributeMapper.insertMDeviceAttribute(mDeviceAttribute);
                        //logger.info("科敏"+mDeviceAttribute.getSerialNumber()+mDeviceAttribute.getAttributeName()+"添加设备最新属性状态成功");
                    }else if (deviceAttribute.getAttributeStatus()!=2){

                        mDeviceAttributeMapper.updateMDeviceAttributeBySerialNumberAndAttributeId(mDeviceAttribute);
                        //logger.info("科敏"+mDeviceAttribute.getSerialNumber()+mDeviceAttribute.getAttributeName()+"更新设备最新属性状态成功");
                    }
                }
            }

            //更新从数据库的数据
            MDeviceAttribute mDeviceAttribute = new MDeviceAttribute();
            List<MDeviceAttribute> mDeviceAttributes = mDeviceAttributeMapper.selectMDeviceAttributeList(mDeviceAttribute);

            for (MDeviceAttribute deviceAttribute : mDeviceAttributes) {

                MDeviceAttribute mDeviceAttribute1 = mDeviceAttributeSlaveMapper.selectMDeviceAttributeBySerialNumberAndAttributeId(deviceAttribute.getSerialNumber(), deviceAttribute.getAttributeId());

                if (mDeviceAttribute1==null){

                    mDeviceAttributeSlaveMapper.insertMDeviceAttribute(deviceAttribute);
                    //logger.info("从数据源添加成功");
                }else {

                    mDeviceAttributeSlaveMapper.updateMDeviceAttributeBySerialNumberAndAttributeId(deviceAttribute);
                    //logger.info("从数据源修改成功");

                }
            }

            logger.info("本次所有设备最新属性更新完成");

        } catch (Exception e) {

            logger.error("数据接口访问失败。");
            logger.error(e.getMessage());
        }

    }


    /**
     * 调用九通接口
     * @return
     */
    private List<Map<String, Object>> getJiuTongData(String serialNumber) throws IOException {


        //调用九通接口接收的集合
        List<Map<String, Object>> ret;
        // 设备MAC
        if (!StringUtils.hasLength(serialNumber)) {
            return null;
        }
        String url = weatherDataUrl + "deviceMac=" + serialNumber;
        //调用九通接口
        Connection.Response res = Jsoup.connect(url).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate").header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3").header("Content-Type", "application/json;charset=UTF-8").header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0").timeout(10000).ignoreContentType(true).execute();
        String body = res.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (!jsonObject.get("message").equals("OK")) {
            return null;
        }

        ret = (List<Map<String, Object>>) jsonObject.get("data");

        return ret;
    }



    /**
     *  科敏Api登陆
     * @param mobile
     * @param password
     * @return
     */
    private Map<String,Object> keMintApiLogin(String mobile,String password) {
        Map<String, Object> ret;

        // 设备MAC
        if (!StringUtils.hasLength(mobile)) {
            return null;
        }
        if (!StringUtils.hasLength(password)) {
            return null;
        }
        try {
            org.jsoup.Connection.Response res = Jsoup
                    .connect(keMinDataUrl + "api/open/login?mobile=" + mobile + "&password=" + password)
                    .header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
                    .timeout(10000).ignoreContentType(true).execute();

            String body = res.body();
            //System.out.println(body);
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(body);
            if (!jsonObject.get("code").equals("0000")) {
                return null;
            }

            ret = (Map<String, Object>) jsonObject.get("data");

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return ret;

    }


    /**
     * 调用科敏接口
     * @return
     */
    private List<Map> getKeMinData(String serialNumber) throws IOException {

        //登陆科敏 拿到token
        Map<String, Object> dataM = keMintApiLogin(mobile, password);
        Base64.Encoder encoder = Base64.getEncoder();
        String token = encoder.encodeToString(dataM.get("token").toString().getBytes());


        List<Map> ret;

        // 设备MAC
        if (!StringUtils.hasLength(serialNumber)) {
            return null;
        }
        if (!StringUtils.hasLength(token)) {
            return null;
        }

        //调用科敏接口
        Connection.Response res = Jsoup.connect(keMinDataUrl + "api/hw/getDeviceTempList?imei=" + serialNumber).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate").header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3").header("Content-Type", "application/json;charset=UTF-8").header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0").header("Authorization",token).timeout(10000).ignoreContentType(true).execute();
        String body = res.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (!jsonObject.get("code").equals("0000")) {
            return null;
        }

         return  (List<Map>) jsonObject.get("data");
    }












}
